<?php

namespace App\Exceptions;

use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Session\TokenMismatchException;
use Symfony\Component\HttpFoundation\Exception\SuspiciousOperationException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Throwable;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Arr;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
//        \Illuminate\Auth\AuthenticationException::class,
//        \Illuminate\Auth\Access\AuthorizationException::class,
//        \Symfony\Component\HttpKernel\Exception\HttpException::class,
//        \Illuminate\Database\Eloquent\ModelNotFoundException::class,
//        \Illuminate\Session\TokenMismatchException::class,
//        \Illuminate\Validation\ValidationException::class,
    ];

    /**
     * A list of the internal exception types that should not be reported.
     *
     * @var array
     */
    protected $internalDontReport = [
//        AuthenticationException::class,
//        AuthorizationException::class,
//        HttpException::class,
//        HttpResponseException::class,
//        ModelNotFoundException::class,
//        SuspiciousOperationException::class,
//        TokenMismatchException::class,
//        ValidationException::class,
    ];

    protected function context()
    {
        return array_merge(
            parent::context(),
            ['request_id' => REQUEST_ID]
        );
    }

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Throwable $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request $request
     * @param Throwable $exception
     * @return \Illuminate\Http\Response
     * @throws Throwable
     */
    public function render($request, Throwable $exception)
    {
        $currentRoute = $request->route();
        $shouldHandleCustom = ($currentRoute && $request->routeIs('api.*')) || $request->expectsJson();
        if ($shouldHandleCustom) {
            $msg = sprintf("%s", $exception->getMessage());
            $data = [
                'params' => $request->all(),
            ];
            if (!app()->environment('production')) {
                $data += [
                    'file' => $exception->getFile(),
                    'line' => $exception->getLine(),
                ];
            }
            if ($exception instanceof ValidationException) {
                $errors = $exception->errors();
                $msg = sprintf("%s", Arr::first(Arr::first($errors)));
                $data['errors'] = $errors;
                return response()->json(normalize($msg, $data), 200);
            } elseif ($exception instanceof AuthenticationException) {
                //未认证，结果码为-1000，前端收到此码需要刷新token
                return response()->json(normalize(RET_REFRESH_TOKEN, $msg, $data), 401);
            } elseif ($exception instanceof HuanbaoException) {
                $data['data'] = $exception->getData();
                return response()->json(normalize($msg, $data), 200);
            } else {
                return response()->json(normalize($msg, $data), 500);
            }
        }
        return parent::render($request, $exception);
    }

    /**
     * Convert an authentication exception into an unauthenticated response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Auth\AuthenticationException  $exception
     * @return \Illuminate\Http\Response
     */
    protected function unauthenticated($request, AuthenticationException $exception)
    {
//        if ($request->expectsJson()) {
//            return response()->json(['error' => 'Unauthenticated.'], 401);
//        }
//
//        return redirect()->guest(route('login'));
    }
}
